// pages/wantedBook/wantedBook.js
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    arr:[],
    wantedbookid:null,
    mwanterid:null,
    mwantername:null,
    mwantedbookname:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    /* 初始化数据库 */
    const db = wx.cloud.database()
    db.collection('wBooks').where
      ({
        handleflag:false
      })
    .get
      ({
        success: res => {

          //date时间格式化 
          for (let i = 0; i < res.data.length; i++) {
            var start = new Date(res.data[i].pubdate)
            var newtime = util.formatTime(start)
            res.data[i].pubdate = newtime
          }

          this.setData({
            arr: res.data
          });
          console.log('数据库查询成功:', res.data)
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //心愿单中处理按钮
  havehandle: function (event) {
    console.log(' event.detail:', event.detail)
    console.log('form_id:', event.detail.formId)

    var that = this

    //1.按照_id在集合中找到此条记录，更新flag状态
    var tempid = event.target.dataset.wantedbookid
    this.setData(
      {
        wantedbookid: tempid,
      })
    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('wBooks').where
      ({
        _id: _.eq(this.data.wantedbookid)
      })
      .get
      ({
        success: res => {
          if (res.data.length == 1) {
            //提前准备发送模版消息需要的数据
            this.setData(
              {
                mwanterid: res.data[0]._openid,
                mwantername: res.data[0].wantername,
                mwantedbookname: res.data[0].title,
              })

            //修改处理的标志位
            res.data[0].handleflag = true
            //更新此条记录
            db.collection('wBooks').doc(res.data[0]._id).set
              ({
                data: {
                  title: res.data[0].title,
                  author: res.data[0].author,
                  publisher: res.data[0].publisher,
                  btype: res.data[0].btype,
                  pubdate: res.data[0].pubdate,
                  wantername: res.data[0].wantername,
                  wanterid: res.data[0].wanterid,
                  wantedtime: res.data[0].wantedtime,
                  handleflag: res.data[0].handleflag,
                }, success: function (res) {
                  wx.showToast({
                    title: '成功',
                    icon: 'success',
                    duration: 1000
                  })
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '../wantedBook/wantedBook',
                    })
                  }, 500)

                  //2.向wanterid发送图书可借通知
              
                  //准备模版数据
                  console.log('getApp()_token:', getApp().globalData.access_token)
                  let _access_token = getApp().globalData.access_token;
                  let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token; 
                  let _jsonData = {
                    access_token: _access_token,
                    // touser: 'ow6NN5VmfGWIwdAbO4kiyqMX8Y28',
                    touser: that.data.mwanterid,
                    template_id: getApp().globalData.bookava,
                    form_id: event.detail.formId,
                    page: "pages/shelter/shelter",
                    data: {
                      "keyword1": { "value": that.data.mwantername, "color": "#173177" },
                      "keyword2": { "value": "《"+that.data.mwantedbookname+"》", "color": "#173177" },
                      "keyword3": { "value": "您想读的图书已经到馆，请尽快来借阅哦。", "color": "#173177" }
                    },
                    //需要放大的关键字
                    // emphasis_keyword: 'keyword1.DATA'
                  }
      
                  //发送模版消息
                  wx.request({
                    url: url,
                    data: _jsonData,
                    method: 'POST',
                    success: function (res) {
                      console.log(res)
                    },
                    fail: function (err) {
                      console.log('request fail ', err);
                    },
                    complete: function (res) {
                      console.log("request completed!");
                    }

                  })


                }, fail: (res) => {
                  console.error
                  wx.showToast({
                    title: '失败',
                    icon: 'success',
                    duration: 1000
                  }),
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '../wantedBook/wantedBook',
                      })
                    }, 500)
                }
              })

            console.log('数据存在:', res.data)
          } else {
            console.log('数据为空！')
          }
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })


  },

})